package com.android.lovely.ui.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.android.lovely.api.service.taskService
import com.android.lovely.api.service.userService
import com.android.lovely.data.GeneratedImageResult
import com.android.lovely.data.ImageGenerationTask
import com.android.lovely.data.RoleHistory
import com.android.lovely.framework.BaseLoadViewModel
import com.android.lovely.framework.launchWithLoading
import com.android.lovely.room.role.CreateRole
import com.android.lovely.room.role.CreateRoleDataBase
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow

/**
 *
 * @author why
 * @date 2025/4/8 16:41
 */
class WorkTaskViewModel: BaseLoadViewModel<ImageGenerationTask>() {


    private val _delete = MutableSharedFlow<Int>(0)
    val delete: SharedFlow<Int> get() = _delete

    private val _statueType = MutableLiveData<Int>()
    val statueType: LiveData<Int> get() = _statueType

    private val _downLoad = MutableSharedFlow<GeneratedImageResult>(0)
    val downLoad: SharedFlow<GeneratedImageResult> get() = _downLoad

    var status: Int? = null

    fun getImgDetail(mapOf: Map<String, Int>) {
        viewModelScope.launchSafety() {
            val data = taskService.getTaskDetails(mapOf)
            _downLoad.emit(data)
        }.onError {
            viewModelScope.launchSafety {
                _downLoad.emit(GeneratedImageResult())
            }
        }
    }

    fun delete(id: Int) {
        viewModelScope.launchWithLoading {
            taskService.deleteImageTask(mapOf("task_id" to id))
            _delete.emit(id)
        }
    }

    override suspend fun requestApi(page: Int, loadSize: Int): List<ImageGenerationTask> {
        return taskService.getImageTasks(
            mapOf(
                "page" to page, "size" to loadSize, "status" to status
            )
        )
    }

    fun update(trans: Int) {
        viewModelScope.launchSafety {
            status =  when (trans) {
                1 -> 1
                2 -> 0
                0 -> null
                else -> -1
            }
            _statueType.value = trans
        }
    }

}